/*
 * NewOrder.java
 *
 * Created on March 26, 2007, 6:30 PM
 */



package edu.byu.isys413.jjenkins.view;
import edu.byu.isys413.jjenkins.data.*;
import java.awt.Color;
import java.security.spec.ECField;
import java.sql.Date;
import java.text.NumberFormat;
import java.util.List;
import javax.swing.DefaultListModel;
import javax.swing.JOptionPane;

/**
 * This form is called to create or view an order.
 * @author byu
 */
public class NewOrder extends javax.swing.JFrame {
    
    /**
     * the transaction for the order
     */
    TransactionBO trans;
    
    
    // Holds transaction lines on the GUI
    /**
     * the model for the JList to display the transaction lines
     */
    DefaultListModel model = new DefaultListModel();
    /**
     * list of transaction lines
     */
    List<TransactionLineBO> li;
    
    
    //Singleton variable
    /**
     * singleton variabel
     */
    private static NewOrder instance = null;
    
    
    /** Creates new form NewOrder */
    private NewOrder() {
        initComponents();
        this.setLocationRelativeTo(null);
        this.pack();
        lstLines.setModel(model);
        txtSKU.requestFocus();
        
    }
    
    
    /**
     * gets a single of this class
     */
    public static synchronized NewOrder getInstance() {
        
        if (instance == null) {
            instance = new NewOrder();
        }
        
        
        return instance;
    }
    
    
    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc=" Generated Code ">//GEN-BEGIN:initComponents
    private void initComponents() {
        jPanel13 = new javax.swing.JPanel();
        jPanel1 = new javax.swing.JPanel();
        txtConversion = new javax.swing.JLabel();
        txtDevelopment = new javax.swing.JLabel();
        txtBackup = new javax.swing.JLabel();
        txtServiceRepair = new javax.swing.JLabel();
        btnFinish = new javax.swing.JButton();
        btnSave = new javax.swing.JButton();
        btnCancel = new javax.swing.JButton();
        jPanel2 = new javax.swing.JPanel();
        jPanel14 = new javax.swing.JPanel();
        jPanel3 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        txtSKU = new javax.swing.JTextField();
        jLabel2 = new javax.swing.JLabel();
        txtQTY = new javax.swing.JTextField();
        jLabel4 = new javax.swing.JLabel();
        txtCoupon = new javax.swing.JTextField();
        btnAdd = new javax.swing.JButton();
        jPanel4 = new javax.swing.JPanel();
        jPanel12 = new javax.swing.JPanel();
        btnDelete = new javax.swing.JButton();
        jLabel6 = new javax.swing.JLabel();
        lblSubTotal = new javax.swing.JLabel();
        jLabel8 = new javax.swing.JLabel();
        lblTax = new javax.swing.JLabel();
        lblTotallable = new javax.swing.JLabel();
        lblTotal = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        cmbStatus = new javax.swing.JComboBox();
        jScrollPane1 = new javax.swing.JScrollPane();
        lstLines = new javax.swing.JList();

        setTitle("Create Order");
        jPanel13.setBorder(javax.swing.BorderFactory.createEmptyBorder(30, 10, 30, 10));
        jPanel13.setPreferredSize(new java.awt.Dimension(150, 360));
        jPanel1.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT));

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("Select Product"));
        jPanel1.setPreferredSize(new java.awt.Dimension(120, 200));
        txtConversion.setFont(new java.awt.Font("Tahoma", 0, 14));
        txtConversion.setForeground(new java.awt.Color(102, 102, 255));
        txtConversion.setText("Conversion");
        txtConversion.setBorder(javax.swing.BorderFactory.createEmptyBorder(25, 1, 25, 1));
        txtConversion.setPreferredSize(new java.awt.Dimension(100, 18));
        txtConversion.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mousePressed(java.awt.event.MouseEvent evt) {
                txtConversionMousePressed(evt);
            }
            public void mouseReleased(java.awt.event.MouseEvent evt) {
                txtConversionMouseReleased(evt);
            }
        });

        jPanel1.add(txtConversion);

        txtDevelopment.setFont(new java.awt.Font("Tahoma", 0, 14));
        txtDevelopment.setForeground(new java.awt.Color(102, 102, 255));
        txtDevelopment.setText("Development");
        txtDevelopment.setBorder(javax.swing.BorderFactory.createEmptyBorder(25, 1, 25, 1));
        txtDevelopment.setPreferredSize(new java.awt.Dimension(100, 18));
        txtDevelopment.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mousePressed(java.awt.event.MouseEvent evt) {
                txtDevelopmentMousePressed(evt);
            }
            public void mouseReleased(java.awt.event.MouseEvent evt) {
                txtDevelopmentMouseReleased(evt);
            }
        });

        jPanel1.add(txtDevelopment);

        txtBackup.setFont(new java.awt.Font("Tahoma", 0, 14));
        txtBackup.setForeground(new java.awt.Color(102, 102, 255));
        txtBackup.setText("Backup");
        txtBackup.setBorder(javax.swing.BorderFactory.createEmptyBorder(25, 1, 25, 1));
        txtBackup.setPreferredSize(new java.awt.Dimension(100, 18));
        txtBackup.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mousePressed(java.awt.event.MouseEvent evt) {
                txtBackupMousePressed(evt);
            }
            public void mouseReleased(java.awt.event.MouseEvent evt) {
                txtBackupMouseReleased(evt);
            }
        });

        jPanel1.add(txtBackup);

        txtServiceRepair.setFont(new java.awt.Font("Tahoma", 0, 14));
        txtServiceRepair.setForeground(new java.awt.Color(102, 102, 255));
        txtServiceRepair.setText("Sevice/Repair");
        txtServiceRepair.setBorder(javax.swing.BorderFactory.createEmptyBorder(25, 1, 25, 1));
        txtServiceRepair.setPreferredSize(new java.awt.Dimension(100, 18));
        txtServiceRepair.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mousePressed(java.awt.event.MouseEvent evt) {
                txtServiceRepairMousePressed(evt);
            }
            public void mouseReleased(java.awt.event.MouseEvent evt) {
                txtServiceRepairMouseReleased(evt);
            }
        });

        jPanel1.add(txtServiceRepair);

        jPanel13.add(jPanel1);

        btnFinish.setText("Finish and Pay");
        btnFinish.setPreferredSize(new java.awt.Dimension(115, 23));
        btnFinish.setRequestFocusEnabled(false);
        btnFinish.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnFinishActionPerformed(evt);
            }
        });

        jPanel13.add(btnFinish);

        btnSave.setText("Save");
        btnSave.setPreferredSize(new java.awt.Dimension(115, 23));
        btnSave.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnSaveActionPerformed(evt);
            }
        });

        jPanel13.add(btnSave);

        btnCancel.setText("Cancel");
        btnCancel.setPreferredSize(new java.awt.Dimension(115, 23));
        btnCancel.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnCancelActionPerformed(evt);
            }
        });

        jPanel13.add(btnCancel);

        getContentPane().add(jPanel13, java.awt.BorderLayout.WEST);

        jPanel2.setLayout(new java.awt.BorderLayout());

        jPanel2.setBorder(javax.swing.BorderFactory.createEmptyBorder(30, 3, 30, 30));
        jPanel14.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT));

        jPanel14.setPreferredSize(new java.awt.Dimension(695, 100));
        jPanel3.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT));

        jPanel3.setMinimumSize(new java.awt.Dimension(30, 33));
        jPanel3.setPreferredSize(new java.awt.Dimension(430, 75));
        jLabel1.setText("Enter SKU of Sale or Rental Item:");
        jLabel1.setBorder(javax.swing.BorderFactory.createMatteBorder(0, 0, 1, 0, new java.awt.Color(0, 0, 0)));
        jLabel1.setPreferredSize(new java.awt.Dimension(400, 15));
        jPanel3.add(jLabel1);

        jLabel3.setText("SKU:");
        jPanel3.add(jLabel3);

        txtSKU.setPreferredSize(new java.awt.Dimension(100, 20));
        txtSKU.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                txtSKUActionPerformed(evt);
            }
        });
        txtSKU.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                txtSKUKeyPressed(evt);
            }
        });

        jPanel3.add(txtSKU);

        jLabel2.setText("QTY:");
        jPanel3.add(jLabel2);

        txtQTY.setText("1");
        txtQTY.setPreferredSize(new java.awt.Dimension(20, 20));
        jPanel3.add(txtQTY);

        jLabel4.setText("Coupon:");
        jPanel3.add(jLabel4);

        txtCoupon.setPreferredSize(new java.awt.Dimension(100, 20));
        jPanel3.add(txtCoupon);

        btnAdd.setText("ADD");
        btnAdd.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnAddActionPerformed(evt);
            }
        });

        jPanel3.add(btnAdd);

        jPanel14.add(jPanel3);

        jPanel2.add(jPanel14, java.awt.BorderLayout.NORTH);

        jPanel4.setLayout(new java.awt.BorderLayout());

        jPanel12.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT));

        btnDelete.setText("Delete");
        btnDelete.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnDeleteActionPerformed(evt);
            }
        });

        jPanel12.add(btnDelete);

        jLabel6.setText("Subtotal:  ");
        jPanel12.add(jLabel6);

        lblSubTotal.setPreferredSize(new java.awt.Dimension(50, 14));
        jPanel12.add(lblSubTotal);

        jLabel8.setText("Tax:   ");
        jPanel12.add(jLabel8);

        lblTax.setPreferredSize(new java.awt.Dimension(50, 14));
        jPanel12.add(lblTax);

        lblTotallable.setText("Total:  ");
        jPanel12.add(lblTotallable);

        lblTotal.setPreferredSize(new java.awt.Dimension(50, 14));
        jPanel12.add(lblTotal);

        jLabel5.setText("Transaction Status:");
        jPanel12.add(jLabel5);

        cmbStatus.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Pending", "Void", "Finished", "Hold" }));
        cmbStatus.setPreferredSize(new java.awt.Dimension(100, 20));
        cmbStatus.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cmbStatusActionPerformed(evt);
            }
        });
        cmbStatus.addPropertyChangeListener(new java.beans.PropertyChangeListener() {
            public void propertyChange(java.beans.PropertyChangeEvent evt) {
                cmbStatusPropertyChange(evt);
            }
        });

        jPanel12.add(cmbStatus);

        jPanel4.add(jPanel12, java.awt.BorderLayout.CENTER);

        jScrollPane1.setBorder(javax.swing.BorderFactory.createTitledBorder("Items On Transaction"));
        lstLines.setBackground(new java.awt.Color(224, 223, 227));
        jScrollPane1.setViewportView(lstLines);

        jPanel4.add(jScrollPane1, java.awt.BorderLayout.NORTH);

        jPanel2.add(jPanel4, java.awt.BorderLayout.CENTER);

        getContentPane().add(jPanel2, java.awt.BorderLayout.CENTER);

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void txtSKUKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtSKUKeyPressed
// TODO add your handling code here:
        //System.out.println("event was"+evt.getID());//always 401
        System.out.println("event was"+evt.getKeyCode());
        if(evt.getKeyCode() == 10){
           processSKU();
        }
    }//GEN-LAST:event_txtSKUKeyPressed

    private void txtSKUActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtSKUActionPerformed
// TODO add your handling code here:
        //System.out.println("event was"+evt.getSource());
    }//GEN-LAST:event_txtSKUActionPerformed
    
    private void btnCancelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCancelActionPerformed
        
        try {
            
            trans.setStatus("void");
            UpdateController.getInstance().post(trans, (CurrentOptsBO)Cache.getInstance().get("currentOpts"));
            Cache.getInstance().touch("currentOpts");
            this.setVisible(false);
        } catch (DataException ex) {
            JOptionPane.showMessageDialog(null,ex.toString(),"Can't save transaction", JOptionPane.ERROR_MESSAGE);
            ex.printStackTrace();
        }
    }//GEN-LAST:event_btnCancelActionPerformed
    /**
     * This method saves the transaction without adding a payment or finishing the transaction
     * @param evt
     */
    private void btnSaveActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSaveActionPerformed
        try {
            // finish Order
            trans.endTransaction();
            
            UpdateController.getInstance().post(trans, (CurrentOptsBO)Cache.getInstance().get("currentOpts"));
            Cache.getInstance().touch("currentOpts");
            this.setVisible(false);
        } catch (DataException ex) {
            JOptionPane.showMessageDialog(null,ex.toString(),"Can't save transaction", JOptionPane.ERROR_MESSAGE);
            ex.printStackTrace();
        }
    }//GEN-LAST:event_btnSaveActionPerformed
    
    /**
     * This method create a transction line and revenue source for a service repair
     * @param evt
     */
    private void txtServiceRepairMouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_txtServiceRepairMouseReleased
        System.out.println("creating rev source");
        txtServiceRepair.setForeground(new Color(102,102,255));
        
    }//GEN-LAST:event_txtServiceRepairMouseReleased
    
    /**
     * This method is used to change the color of the text
     * @param evt
     */
    private void txtServiceRepairMousePressed(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_txtServiceRepairMousePressed
        txtServiceRepair.setForeground(new Color(4,4,4));
        // Set the color back to normal
        txtBackup.setForeground(new Color(102,102,255));
        
        
        try{
            /*The next couple of statements set information that is avaiable in the View*/
            // creates transaction line
            TransactionLineBO line = TransactionLineDAO.getInstance().create();
            
            // sets transaction
            line.setTransaction(trans);
            
            // sets Coupon
            if(!(txtCoupon.getText().equals(""))){
                line.setCoupon(ConceptualCouponDAO.getInstance().read(txtCoupon.getText()));
            }
            
            // Creates Revenue Source
            ServiceRepairBO revBO = (ServiceRepairBO)((ServiceRepairDAO)RevenueSourceFactory.getInstance().getDAO("service_repair")).create();
            
            // Set transaction line
            revBO.setLine(line);
            
            // Set Quantity
            revBO.setQuantity(Double.parseDouble(txtQTY.getText()));
            
            // Displays subRevenueSource View to finish collecting data unique to the revenue source
            ServiceRepairGUI view = (ServiceRepairGUI)RSGUIFACTORY.getInstance().getGUI("service_repair");
            
            // passes the revenueSource object to the sub view to populate it with the data that is uniqe to that revenue source
            view.populate(revBO);
            
            // sets revenue source to line
            line.setRevenueSource(revBO);
            
            
            // adds line to transaction
            trans.addTransactionLine(line);
            
            
        }catch(DataException ex){
            JOptionPane.showMessageDialog(null,ex.toString(),"Error Creating Rental", JOptionPane.ERROR_MESSAGE);
            ex.printStackTrace();
        }
        
        
    }//GEN-LAST:event_txtServiceRepairMousePressed
    
    /**
     * This method creates a transcation line and revenue source for backup
     * @param evt
     */
    private void txtBackupMouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_txtBackupMouseReleased
        // Set the color back to normal
        txtBackup.setForeground(new Color(102,102,255));
        
        
        try{
            /*The next couple of statements set information that is avaiable in the View*/
            // creates transaction line
            TransactionLineBO line = TransactionLineDAO.getInstance().create();
            
            // sets transaction
            line.setTransaction(trans);
            
            // sets Coupon
            if(!(txtCoupon.getText().equals(""))){
                line.setCoupon(ConceptualCouponDAO.getInstance().read(txtCoupon.getText()));
            }
            
            // Creates Revenue Source
            BackupBO revBO = (BackupBO)((BackupDAO)RevenueSourceFactory.getInstance().getDAO("backup")).create();
            
            // Set transaction line
            revBO.setLine(line);
            
            // Set Quantity
            revBO.setQuantity(Double.parseDouble(txtQTY.getText()));
            
            // Displays subRevenueSource View to finish collecting data unique to the revenue source
            BackupGUI view = (BackupGUI)RSGUIFACTORY.getInstance().getGUI("backup");
            
            // passes the revenueSource object to the sub view to populate is with the data that is uniqe to that revenue source
            view.populate(revBO);
            
            // sets revenue source to line
            line.setRevenueSource(revBO);
            
            
            // adds line to transaction
            trans.addTransactionLine(line);
            
            
        }catch(DataException ex){
            JOptionPane.showMessageDialog(null,ex.toString(),"Error Creating Rental", JOptionPane.ERROR_MESSAGE);
            ex.printStackTrace();
        }
    }//GEN-LAST:event_txtBackupMouseReleased
    
    /**
     * This method is used to change the color of the text
     * @param evt
     */
    private void txtBackupMousePressed(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_txtBackupMousePressed
        txtBackup.setForeground(new Color(4,4,4));
    }//GEN-LAST:event_txtBackupMousePressed
    
    /**
     * This method creates a transactionline and revenueSource for a development
     * @param evt
     */
    private void txtDevelopmentMouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_txtDevelopmentMouseReleased
    
        System.out.println("creating rev source");
        txtDevelopment.setForeground(new Color(102,102,255));      
        PrintOrderGUI.getInstance();
       
//       try{
//            /*The next couple of statements set information that is avaiable in the View*/
//            // creates transaction line
//            TransactionLineBO line = TransactionLineDAO.getInstance().create();
//            
//            // sets transaction
//            line.setTransaction(trans);
//            
//            // Creates Revenue Source
//            PrintOrderLineRS revBO = (PrintOrderLineRS)((PrintOrderLineRSDAO)RevenueSourceFactory.getInstance().getDAO("print_order")).create();
//            
//            // Set transaction line
//            revBO.setLine(line);
//            
//            // Set Quantity
//            revBO.setQuantity(Double.parseDouble(txtQTY.getText()));
//            
//            // Displays subRevenueSource View to finish collecting data unique to the revenue source
//            PrintOrderGUI view = (PrintOrderGUI)RSGUIFACTORY.getInstance().getGUI("print_order");
//            //view.setVisible(true);
//            
//            // passes the revenueSource object to the sub view to populate is with the data that is uniqe to that revenue source
//            view.populate(revBO);
//            
//            // sets revenue source to line
//            line.setRevenueSource(revBO);
//            
//            
//            // adds line to transaction
//            trans.addTransactionLine(line);
//            
//            
//       }catch(DataException ex){
//            JOptionPane.showMessageDialog(null,ex.toString(),"Error Creating Rental", JOptionPane.ERROR_MESSAGE);
//            ex.printStackTrace();
//      
//       }                                 
    }//GEN-LAST:event_txtDevelopmentMouseReleased
    
    /**
     * This method is used to change the color of the text
     * @param evt
     */
    private void txtDevelopmentMousePressed(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_txtDevelopmentMousePressed
        txtDevelopment.setForeground(new Color(4,4,4));
    }//GEN-LAST:event_txtDevelopmentMousePressed
    
    /**
     * This method opens the payment window posts the transaction
     * @param evt
     */
    private void btnFinishActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnFinishActionPerformed
        try{
            // finish Order
            trans.endTransaction();
            
            // create payment
            
            PaymentBO payment = PaymentDAO.getInstance().create();
            PaymentGUI view = PaymentGUI.getInstance();
            System.out.println(view);
            view.populate(payment);
            
            
        }catch(DataException ex){
            JOptionPane.showMessageDialog(null,ex.toString(),"Cannot end transaction", JOptionPane.ERROR_MESSAGE);
        }
    }//GEN-LAST:event_btnFinishActionPerformed
    
    /**
     * This method post the transaction to the database
     * @param payment
     */
    public void postTransaction(PaymentBO payment){
        try{
            // Post transaction
            System.out.println(payment);
            //need to set returning status to returned
            List lines = trans.getTransactionList();
            for(int i=0;i<lines.size();i++){
                //TransactionLineBO trashline = (TransactionLineBO) lines.get(i);
                if(((TransactionLineBO)lines.get(i)).getStatus().equals("returning")){
                    ((TransactionLineBO)lines.get(i)).setStatus("returned");
                }
            }//for
            UpdateController.getInstance().post(trans,payment,(CurrentOptsBO)Cache.getInstance().get("currentOpts"));
            Cache.getInstance().touch("currentOpts");
            this.setVisible(false);
            SaleReturn2.getInstance().dispose();
            SaleReturn.getInstance().dispose();
            
            
        }catch(DataException ex){
            JOptionPane.showMessageDialog(null,ex.toString(),"Cannot post transaction", JOptionPane.ERROR_MESSAGE);
            ex.printStackTrace();
        }
    }
    
    /**
     * This method removes a tranasactionline from the transaction. It does not remove the transaction line form the database
     * @param evt
     */
    private void btnDeleteActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnDeleteActionPerformed
        
        // removes transaction
        trans.removeTransactionLine(li.get(lstLines.getSelectedIndex()).getId());
        // repopulates the list
        populateTransactionLines();
        
        
    }//GEN-LAST:event_btnDeleteActionPerformed
    
    /**
     * thie method creates a transcation line and revenue source for a conversion
     * @param evt
     */
    private void txtConversionMouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_txtConversionMouseReleased
        System.out.println("creating rev source");
        txtConversion.setForeground(new Color(102,102,255));
        ConversionGUI.getInstance();
        
//        try{
//            /*The next couple of statements set information that is avaiable in the View*/
//            // creates transaction line
//            TransactionLineBO line = TransactionLineDAO.getInstance().create();
//            
//            // sets transaction
//            line.setTransaction(trans);
//            
//            // Creates Revenue Source
//            Conversion revBO = (Conversion)((ConversionDAO)RevenueSourceFactory.getInstance().getDAO("conversion")).create();
//            
//            // Set transaction line
//            revBO.setLine(line);
//            
//            // Set Quantity
//            revBO.setQuantity(Double.parseDouble(txtQTY.getText()));
//            
//            // Displays subRevenueSource View to finish collecting data unique to the revenue source
//            ConversionGUI view = (ConversionGUI)RSGUIFACTORY.getInstance().getGUI("conversion");
//            //view.setVisible(true);
//            
//            // passes the revenueSource object to the sub view to populate is with the data that is uniqe to that revenue source
//            view.populate(revBO);
//            
//            // sets revenue source to line
//            line.setRevenueSource(revBO);
//            
//            
//            // adds line to transaction
//            trans.addTransactionLine(line);
//            
//            
//       }catch(DataException ex){
//            JOptionPane.showMessageDialog(null,ex.toString(),"Error Creating Rental", JOptionPane.ERROR_MESSAGE);
//            ex.printStackTrace();
//      
//       }                                                              
//        
    }//GEN-LAST:event_txtConversionMouseReleased
    
    /**
     * This method is used to change the color of the text
     */
    private void txtConversionMousePressed(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_txtConversionMousePressed
        
        txtConversion.setForeground(new Color(4,4,4));
        
    }//GEN-LAST:event_txtConversionMousePressed
    
    private void cmbStatusPropertyChange(java.beans.PropertyChangeEvent evt) {//GEN-FIRST:event_cmbStatusPropertyChange
                                                                                                    }//GEN-LAST:event_cmbStatusPropertyChange
    
    /**
     * This method changes the status of the transaction
     * @param evt
     */
    private void cmbStatusActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cmbStatusActionPerformed
        try{
            trans.setStatus((String)cmbStatus.getSelectedItem());
        }catch(DataException ex){
            JOptionPane.showMessageDialog(null,ex.toString(),"Cannot change status of transaction", JOptionPane.ERROR_MESSAGE);
        }
    }//GEN-LAST:event_cmbStatusActionPerformed
    
    /**
     * This method adds a rental or sale item to the transactionline and to the transaction. It checks to see if the item scaned is a rental or a sale and creates the appropriate revenue source. If it is a rental additional information si colelacted
     * @param evt
     */
    private void btnAddActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAddActionPerformed
            /* TODO: This method should read in the SKU, determine if is a sale
             * or a rental and then create the appropriate revenue source*/
        //need to determine here, just put this now for testing --rick
        processSKU();
       
        
    }//GEN-LAST:event_btnAddActionPerformed
    
    
    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                try{
                    CurrentOptsBO opts = CurrentOptsDAO.getInstance().create();
                    opts.SignIn("emp1", "sto1");
                    CustomerBO cust = new CustomerBO();
                    
                    NewOrder.getInstance().loadForm(cust);
                }catch(DataException ex){
                    System.out.println("can't create currentopts");
                }
            }
        });
    }
    
    /**
     * This method oads the form with a new transction. A customer is passed in from the select customer gui
     * @param cust
     */
    public void loadForm(CustomerBO cust){
        try{
            // Creates new transaction and sets defaults
            
            trans = TransactionDAO.getInstance().create();
            trans.setCustomer(cust);
            trans.setType("Sale");
            trans.setDate(new Date(System.currentTimeMillis()));
           
            
            trans.setCurrentOpts((CurrentOptsBO) Cache.getInstance().get("currentOpts"));
            
            // Sets the status
            cmbStatus.setSelectedItem(trans.getStatus());
            populateTransactionLines();
            
            this.setVisible(true);
        }catch(DataException ex){
            JOptionPane.showMessageDialog(null,ex.toString(),"Can't open new transaction", JOptionPane.ERROR_MESSAGE);
        }
    }
    
    /**
     * This method is used to view an existing transction. From this view you can edit the transaction if the status is not finished
     * @param transaction
     */
    public void loadForm(TransactionBO transaction){
        btnDelete.setText("Delete");
        trans = transaction;
        System.out.println("testing");
        System.out.println(trans.getStatus());
        cmbStatus.setSelectedItem(trans.getStatus());
        // Adds the items to the GUI in a list
        populateTransactionLines();
    }
    /**
     *this method basically just calls the two other loadForms.
     *this is needed for sale returns, where i will pass in a cust and a transation and the store must refund money
     *
     *@param cust
     *@param trans
     *
     */
    public void loadForm(CustomerBO cust, TransactionBO trans){
        System.out.println("starting return load form");
        loadForm(cust);
        loadForm(trans);
        trans.setType("return");
        trans.setCustomer(cust);
        this.setVisible(true);
    }//cust, trans
    
    /**
     * This method populates the JList used to hold the transaction lines
     */
    public void populateTransactionLines(){
        try{
            System.out.println("!!!!!trans type is "+trans.getType());

            NumberFormat currency = NumberFormat.getCurrencyInstance();
            trans.endTransaction();
            lblSubTotal.setText(currency.format(trans.getSubtotal()));
            lblTax.setText(currency.format(trans.getTax()));
            lblTotal.setText(currency.format(trans.getTotal()));
            

            model.removeAllElements();
            
            
            // List of all interesets
            li =  trans.getTransactionList();
            
            
            // creaetes entries
            for(int i = 0; i < li.size(); i++){
                TransactionLineBO line =li.get(i);
                String description = "-";
                String quan = "-";
                String coupon = "-";
                
                //checks to see if there is a revenue source
                description = line.getRevenueSource().getDescription();
                
                quan = line.getRevenueSource().getQuantity() + "";
                double price = line.getSubtotal();
                
                
                // This add space onto the description to have uniform formatting
                while(description.length()<35){
                    description += " ";
                }
                
                //checks to see if there is a coupon
                if(line.getCouponID() != null){
                    coupon = currency.format(line.getCoupon().getAmount());
                }
                String strLine  =description + "           quantity:  " + quan +   "        coupon:  " + coupon + "         price:  " + currency.format(price);
                
                model.addElement(strLine);
                
                this.setVisible(true);
            }
        }catch(DataException ex){
            JOptionPane.showMessageDialog(null,ex.toString(),"Error adding item to View", JOptionPane.ERROR_MESSAGE);
        }
        
        
    }

    private void processSKU() {
         String sku = txtSKU.getText();
         txtSKU.setText("");
        System.out.println("you want item "+sku);
        TransactionLineBO line = null;
        
        try{
            line = TransactionLineDAO.getInstance().create();
            
            // sets transaction
            line.setTransaction(trans);
            
            // sets Coupon
            if(!(txtCoupon.getText().equals(""))){
                line.setCoupon(ConceptualCouponDAO.getInstance().read(txtCoupon.getText()));
            }
        }catch(DataException e){
            e.printStackTrace();
        }
        if(sku.startsWith("p")){
            System.out.println("this is a physical product!");
            //now how to figure out if it is for sale or for rent?????
            //sku has the prefix to determine wether it's sale or rental
            if(sku.startsWith("ps")){
                //this is a sale
                String [] salesku = sku.split("ps", 2);
                try {
                   //revBO is a rentalBO with it's own guid
                        SaleBO revBO = (SaleBO)((SaleDAO)RevenueSourceFactory.getInstance().getDAO("sale")).create();
                        //revBO.setDescription("this is sale 1");
                        //rent id is the id of a physicalBO with serial num of the sku enterd in
                        //ie. sku is sku66, physicalID is productID or product66
                        String forSaleID = PhysicalDAO.getInstance().getBySerialNum(salesku[1]).getId();
                        //rentid = product66
                        System.out.println("saleid "+forSaleID);
                        
                        ForSaleBO forSale = (ForSaleBO)ForSaleDAO.getInstance().read(forSaleID);
                        //reads product66
                        
                        System.out.println("This is a sale item"+forSale.getId());
                        
                        revBO.setForSale(forSale);
                        revBO.setQuantity(Integer.parseInt(txtQTY.getText()));
                        revBO.setLine(line);
                        line.setRevenueSource(revBO);
                        line.setTransaction(trans);
                        RevenueSourceFactory.getInstance().getDAO("sale").save(revBO);
                        revBO.calcPrice();
                        revBO.createDescription();
                        
                        trans.addTransactionLine(line);
                        
                        populateTransactionLines();


//need to change rs factory, and make sure saleDAO is this.insert((SaleBO)object, conn)
//also need to find a way to pull the description from conceptual table  
              
                    
                } catch (DataException ex) {
                    ex.printStackTrace();
                }
                
            }else if(sku.startsWith("pr")){
                //this is a rental
                String[] salesku = sku.split("pr", 2);
                try{
                    MemberBO memb = trans.getCustomer().getMember();
                    if(memb == null){
                        JOptionPane.showMessageDialog(null, "You Must Be a Member to Rent Items");
                    }else{
                        RentalBO revBO = (RentalBO)((RentalDAO)RevenueSourceFactory.getInstance().getDAO("rental")).create();
                        
                        String forRentID = PhysicalDAO.getInstance().getBySerialNum(salesku[1]).getId();
                        System.out.println("rentid "+forRentID);
                        ForRentBO forRent = (ForRentBO)ForRentDAO.getInstance().read(forRentID);
                        forRent.setTimesRented(forRent.getTimesRented() + 1);
                        forRent.setCurrentRental(revBO);
                        ((ForRentDAO)ForRentDAO.getInstance()).save(forRent);
                        System.out.println("This is a rental item");
                        
                        revBO.setForRent(forRent);
                        revBO.setQuantity(Integer.parseInt(txtQTY.getText()));
                        revBO.setLine(line);
                        line.setRevenueSource(revBO);
                        line.setTransaction(trans);
                        
                        RentalGUI view = (RentalGUI)RSGUIFACTORY.getInstance().getGUI("rental");
                        
                        view.populate(revBO);
                        
                        trans.addTransactionLine(line);
                    }
                }catch(DataException e){
                    e.printStackTrace();
                }
            }
        }else{//if not a physical product, this must be a conceptual product
            //need to read the sku from conceptual
            //then read the product from product to get the price
            try{
            sku = txtSKU.getText();
            System.out.println("this is a conceptual item. will be implemented soon");
            /*
            SaleBO revBO = (SaleBO)((SaleDAO)RevenueSourceFactory.getInstance().getDAO("sale")).create();
                        //revBO.setDescription("this is sale 1");
                        //rent id is the id of a physicalBO with serial num of the sku enterd in
                        //ie. sku is sku66, physicalID is productID or product66
                        //String forSaleID = PhysicalDAO.getInstance().getBySerialNum(sku).getId();
                        //rentid = product66
                        //System.out.println("saleid "+forSaleID);
            
                        //i dont want a forsale bo because this is conceptual, not physical
                        //ForSaleBO forSale = ForSaleDAO.getInstance().read(forSaleID);
                        //reads product66
                        
                        System.out.println("This is a sale item"+forSale.getId());
                        
                        revBO.setForSale(forSale);
                        revBO.setQuantity(Integer.parseInt(txtQTY.getText()));
                        revBO.setLine(line);
                        line.setRevenueSource(revBO);
                        line.setTransaction(trans);
                        RevenueSourceFactory.getInstance().getDAO("sale").save(revBO);
                        revBO.calcPrice();
                        revBO.createDescription();
                        
                        trans.addTransactionLine(line);
                        
                        populateTransactionLines();
             */
            } catch(Exception exception){
                exception.printStackTrace();
            }
        }//else. 
    }
    
    
    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnAdd;
    private javax.swing.JButton btnCancel;
    private javax.swing.JButton btnDelete;
    private javax.swing.JButton btnFinish;
    private javax.swing.JButton btnSave;
    private javax.swing.JComboBox cmbStatus;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel8;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel12;
    private javax.swing.JPanel jPanel13;
    private javax.swing.JPanel jPanel14;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JPanel jPanel4;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JLabel lblSubTotal;
    private javax.swing.JLabel lblTax;
    private javax.swing.JLabel lblTotal;
    private javax.swing.JLabel lblTotallable;
    private javax.swing.JList lstLines;
    private javax.swing.JLabel txtBackup;
    private javax.swing.JLabel txtConversion;
    private javax.swing.JTextField txtCoupon;
    private javax.swing.JLabel txtDevelopment;
    private javax.swing.JTextField txtQTY;
    private javax.swing.JTextField txtSKU;
    private javax.swing.JLabel txtServiceRepair;
    // End of variables declaration//GEN-END:variables
    
}
